import React, { useRef, useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, FormProps, Input, message } from 'antd';
import request from '../utils/request';
import styles from '../style/blog.module.less'
import MarkdownEditor from '../components/MdEditor';
import { useLocation, useNavigate } from 'react-router-dom';

const { TextArea } = Input;
type FieldType = {
  content: string
  remark: string
  cover: string
  tag: string
  title: string
  type?: number
}
const initValues = {
  content: '',
  remark: '',
  cover: '',
  tag: '',
  title: ''
}

const Blog: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const location = useLocation()
  const [imageUrl, setImageUrl] = useState<string>(location.state?.blog?.cover);
  const fileRef = useRef<HTMLInputElement>(null)
  const navigate = useNavigate()
  const editValues = {
    ...initValues,
    ...location.state?.blog
  }

  const onFileChange = async () => {
    if (fileRef.current?.files) {
      setLoading(true)
      // 验证文件
      console.log(fileRef.current.files, 'files')
      // 上传文件
      const formData = new FormData()
      formData.append('file', fileRef.current.files[0])
      const result = await request('/api/load', {
        method: 'POST',
        data: formData
      })
      const md5 = result.data?.data?.md5
      const imgSrc = md5 ? `/api/load/${md5}` : null
      imgSrc && setImageUrl(imgSrc)
      imgSrc && form.setFieldValue('cover', imgSrc)
      setLoading(false)
    }
  }
  const onClickFileButton = () =>  {
    if (fileRef.current) {
      fileRef.current.click()
    }
  }
  const handleDeleteCover = () => {
    setImageUrl('')
    form.setFieldValue('cover', '')
  }
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    // 校验数据
    console.log(values, 'form-data');

    if (location.state.blog) { // 编辑
      const result = await request(`/api/blog/${location.state.blog.id}`, {
        method: 'PUT',
        data: {
          ...values,
          type: 0, // 0-mardown, 1-richtext
        }
      })
      if (result.data.msg === '修改成功') {
        message.success(result.data.msg)
      }
    } else { // 新增
      const result = await request('/api/blog', {
        method: 'POST',
        data: {
          ...values,
          type: 0, // 0-mardown, 1-richtext
        }
      })
      if (result.data.msg === '新增成功') {
        message.success(result.data.msg)
      }
    }
    // 路由到首页
    navigate('/')
    
  }
  const uploadButton = (<>
    <input 
      ref={fileRef}
      type="file" 
      style={{display: 'none'}} 
      onChange={onFileChange}
    />
    <button 
      type="button"
      onClick={onClickFileButton}
      className={styles.coverUploader}
    >
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  </>);
  return (
    <div className={styles.container}>
      <div className={styles.form}>
        <Form
          layout={'vertical'}
          form={form}
          onFinish={onFinish}
          initialValues={editValues}
        >
          <Form.Item label="标题" name='title' >
            <Input />
          </Form.Item>
          <Form.Item label="概要" name='remark'>
            <TextArea  rows={2} maxLength={255} />
          </Form.Item>
          <Form.Item name="cover" style={{display: 'none'}}>
            <Input />
          </Form.Item>
          <Form.Item label="封面">
            {imageUrl 
              ? (<>
                <button onClick={handleDeleteCover} style={{marginBottom: '8px'}}>删除封面</button>
                <img src={imageUrl} alt="avatar" style={{ width: '100%', borderRadius: '5px' }} />
              </>) 
              : uploadButton}
          </Form.Item>
          <Form.Item label="标签" name='tag'>
            <Input  />
          </Form.Item>
          <Form.Item label="文章" name="content">
            <MarkdownEditor />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType='submit'>保存</Button>
            <Button style={{marginLeft: 15}} onClick={()=>navigate(-1)}>取消</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Blog